<script lang="ts">
import { useAntdForm } from '@peng_kai/kit/antd';
import { ApiError } from '@peng_kai/kit/request';
import { InputOtp } from '~/components/input';
import { useModalBindHash } from '~/composables/url';
import { noticeMeta } from '~/composables/useMeta';
import { sendEmailAgainPopup } from './SendEmailAgain.vue';

function useCountdownProps(enabledCountdown = false) {
  const finished = ref(!enabledCountdown);
  const props = reactive({
    value: enabledCountdown ? Date.now() + 1000 * 60 : 0,
    onFinish() {
      finished.value = true;
    },
  });

  const resume = () => {
    props.value = Date.now() + 1000 * 60;
    finished.value = false;
  };

  return reactive({ finished, props, resume });
}

export const verifyEmailPopup = useAntdModal(
  // eslint-disable-next-line import/no-self-import
  defineAsyncComponent(() => import('./VerifyEmail.vue')),
  {
    title: computed(() => $t('aQjxrjt9lbVemAeJpXbzk')),
    wrapClassName: 'ant-cover__Modal-drawer',
    width: 400,
    centered: true,
    maskClosable: false,
    footer: null,
    rejectOnClose: true,
    opener() {
      // /#modal=verifyEmail&email=18777215778%40163.com&verifyCode=560260&type=3
      const isAuthed = useAuthed();

      useModalBindHash({
        modalName: 'verifyEmail',
        requireParamKeys: ['type'],
        conds: [hashParams => hashParams.get('type') === '2' ? isAuthed.value : true],
        isOpen: () => !!verifyEmailPopup.modalProps.open,
        close: () => verifyEmailPopup.close(),
        open(hashParams) {
          verifyEmailPopup.open({
            email: hashParams.get('email') || undefined,
            verifyCode: hashParams.get('verifyCode') || undefined,
            type: Number(hashParams.get('type')!),
          });
        },
      });
    },
  },
);
</script>

<script setup lang="ts">
const props = defineProps<{
  email?: string;
  enabledCountdown?: boolean;
  /** 验证类型  1.注册；2.绑定；3.忘记密码 */
  type: number;
  verifyCode?: string;
  onClose?: () => void;
  onConfirm?: () => void;
}>();

const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);
const getEmailRef = computed(() => props.email || userInfo.value?.email || '');

const cd = useCountdownProps(props.enabledCountdown);

const form = useAntdForm({
  type: {
    value: props.type,
  },
  email: {
    value: getEmailRef.value,
  },
  verify_code: {
    value: props.verifyCode || '',
    rules: [{ required: true, type: 'string', message: $t('3NDbTzuf0Zdk0rSpj6Rkb') }],
  },
});

const verifyEmailMut = useMutation({
  mutationKey: [apis.apiEmailVerify.id, toRef(props, 'type')],
  mutationFn: apis.apiEmailVerify.setDefaultConfig({ successMessage: $t('wbo66vOaVfNMoPl0I2uT') }),
  onSuccess(res: any) {
    if (props.type === 1 && res?.uid) {
      noticeMeta().register({ plateform: 'google', id: res?.uid });
    }
    userStore.userInfoQry.refetch();
    props.onConfirm?.();
  },
  onError(e) {
    const isApiError = e instanceof ApiError;
    // 邮箱验证码不正确或已过期
    if (isApiError && e.code === 15026) {
      form.state.verify_code = '';
    }
  },
});

const getIsLoadingRef = computed(() => verifyEmailMut.isPending.value);

function confirmVerifyEmail() {
  verifyEmailMut.mutate({ requestBody: form.state });
}

function openAgain() {
  sendEmailAgainPopup.open({ email: getEmailRef.value, type: props.type, onSuccess: cd.resume });
}
</script>

<template>
  <div bodyClass="text-sm">
    <div class="text-sys-text-body">
      {{ $t('dGidFaScfnTwMh8tC7R3e') }}: <span class="text-green">{{ getEmailRef }}</span>.
    </div>

    <AForm
      v-bind="form.props" class="ant-cover__Form-compact mt-5" hideRequiredMark :disabled="getIsLoadingRef" layout="vertical"
      @finish="confirmVerifyEmail"
    >
      <AFormItem v-bind="form.itemProps.verify_code" :label="$t('vrOaTrsSDoDwKhZqxWG')">
        <InputOtp v-model:value="form.state.verify_code" />
      </AFormItem>
      <AButton
        class="ant-cover__Button-3d-primary mt-4" type="primary" block htmlType="submit"
        :disabled="getIsLoadingRef" :loading="getIsLoadingRef"
      >
        {{ $t('fVhxPoy2u9I4Q6dqrMh') }}
      </AButton>
    </AForm>

    <!-- 重发邮箱验证 -->
    <div class="mt-4 cursor-pointer text-center text-yellow" :class="{ 'op-50 !cursor-not-allowed': !cd.finished || getIsLoadingRef }">
      <span v-if="cd.finished" @click="openAgain">{{ $t('lkYtccE6GPbgEb0aOqMdc') }}</span>
      <I18nT v-else keypath="ghOfUynvQvzg4XBd07Ao" tag="span">
        <template #time>
          &nbsp;<AStatisticCountdown class="ant-cover__StatisticCountdown-inline-inherit" v-bind="cd.props" />&nbsp;
        </template>
      </I18nT>
    </div>

    <!-- 提示 -->
    <div class="tips mt-10">
      <div class="mb-2">
        {{ $t('11Fch8BsE0Ykip4i69Xhx') }}
      </div>
      <ul class="text-sys-text-body">
        <li>{{ $t('h1jtl4Zx0sRilBjXCpL') }}</li>
        <li>{{ $t('77sjXsuWgAzTDzlqnJijC') }}</li>
      </ul>
    </div>

    <sendEmailAgainPopup.PresetComponent />
  </div>
</template>

<style lang="scss" scoped>
.tips {
  ul {
    padding-left: 1.5em;
    list-style-position: outside;
    list-style-type: disc;
  }

  li {
    list-style-image: url('/src/assets/icons/warn.svg');
  }
}
</style>
